package com.leo.chapter08;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 定制Thead基类
 *      指定了线程的名字
 *      设置UncaughtExceptionHandler向log中写入日志
 *      维护一些统计信息，线程的创建数和存活数
 *      线程被创建和终止写入日志
 * @author xuexiaolei
 * @version 2017年10月18日
 */
public class MyAppThread extends Thread {
    public static final String DEFAULT_NAME = "MyAppThread";
    private static volatile boolean debugLifecycle = false;
    private static final AtomicInteger created = new AtomicInteger();
    private static final AtomicInteger alive = new AtomicInteger();
    private static final Logger log = Logger.getAnonymousLogger();

    public MyAppThread(Runnable r){
        this(r, DEFAULT_NAME);
    }
    public MyAppThread(Runnable r, String poolName) {
        super(r, poolName + "-" + created.incrementAndGet());
        setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override public void uncaughtException(Thread t, Throwable e) {
                log.log(Level.SEVERE, "UNCAUGHT in thread " + t.getName(), e);
            }
        });
    }

    @Override public void run(){
        boolean debug = debugLifecycle;
        if (debug){ log.log(Level.FINE, "Created " + getName()); }
        try {
            alive.incrementAndGet();
            super.run();
        }finally {
            alive.decrementAndGet();
            if (debug){ log.log(Level.FINE, "Exiting " + getName()); }
        }
    }

    public static int getThreadsCreated() { return created.get(); }
    public static int getThreadsAlive() { return alive.get(); }
    public static boolean isDebugLifecycle() { return debugLifecycle; }
    public static void setDebugLifecycle(boolean debugLifecycle) { MyAppThread.debugLifecycle = debugLifecycle; }
}
